<script setup lang="ts">
import { ref } from 'vue'
import saveBlob from "save-blob"
import { getKeystore } from '~/api'

const generated = ref(false)
const confirmed = ref(false)

const router = useRouter()
const go = (target: string) => router.push(target)

const keystores = ref(null as any)

const init = async () => {
  const mnemonic = localStorage.getItem('mnemonic') as string
  const password = localStorage.getItem('password') as string
  const chain = (localStorage.getItem('chain') as string).toLowerCase()
  const start_index = localStorage.getItem('start_index') as string
  const validator_number = localStorage.getItem('validator_number') as string
  if (!mnemonic || !password || !chain) {
    go('/')
  }
  const data = await getKeystore(mnemonic, password, chain, start_index, validator_number)
  localStorage.setItem('deposit_data', JSON.stringify(data.deposit_data))
  localStorage.setItem('keystore', JSON.stringify(data.keystore))
  keystores.value = data.keystore
  generated.value = true
}



const download = (i: number) => {
  const data = JSON.stringify(keystores.value[i])
  const fileBlob = new Blob([data], {"type" : "text/plain"})
  saveBlob(fileBlob, `keystore${i}.json`)
}

onMounted(() => init())
</script>

<template>
  <div class="page-send">
    <div class="card">
      <div class="title">Step (3/4): Save Keystore</div>
      <div v-if="!generated">Generate keystore and transaction infomation for you...</div>
      <div v-else>
        <div>
          Download you keystore here. This is
          <b>very important</b>! your validator node need this!
        </div>
        <div>
          <div class="line mt-2" v-for="(item, index) in keystores">
            <!-- <div>Keystore (Index: {{ index }})</div> -->
            <div class="btn-in-card mr-2"  @click="download(index)">Download(Index: {{index}})</div>
          </div>
        </div>
        
        <div class="line mt-8">
          <input type="checkbox" v-model="confirmed">
          <div class="ml-1">I have already down load my keystore.</div>
        </div>
        <div v-show="confirmed" class="btn-in-card mt-4" @click="go('/send')">Next</div>
      </div>
      
    </div>

    <!-- <div>1.</div>
    <div>Download your keystore here! This is very important, your validator will use this.</div>
    <div>Download KeyStore</div>

    <div>2.</div>
    <div>Transaction infomation for your deposit has been generated</div>
    <div>Download Detail</div>
    <div>Send Transcation</div>-->
  </div>
</template>

<style>
.page-send {
  padding: 15px;
}
</style>